//-------------------------------------------------------------------
//	Copyright (c) 2012-2014 Zhirnov Andrey
//	This file is part of the "UXGEN-ES" project.
//	See copyright notice in "Engine.h".
//-------------------------------------------------------------------

#include "Utils/Sound/SoundConverter.h"
#include "Shared/Resources/ResourceFileInfo.h"


namespace Engine
{
namespace Utils
{

#	include "Shared/Resources/SoundHeader.h"


	// destructor
	SoundConverter::~SoundConverter ()
	{
	}


	// LoadConfig
	bool SoundConverter::LoadConfig (uni_c_string filename, uni_c_string outputPath, bool clearOutputDir)
	{
		static_obj_tree_t	cfg_tree;
		MetaSoundList		obj;

		cfg_tree.Push( TConfigObjInfo( GetMetaClass().GetSetIter( obj ), null ) );
			
		const string	input_path = FileAddressUtils::GetPath( filename );

		_core->Config()->ClearDerectories();
		_core->Config()->AddDirectory( input_path );

		CHECK_ERR( _core->Parse( filename, cfg_tree ) );


		string	input_dir;
		string	output_dir;

		FileAddressUtils::BuildPath( input_dir, input_path, obj.inputDir );
		FileAddressUtils::BuildPath( output_dir, outputPath, obj.outputDir );
		
		// create output dir
		if ( not FileSystem::IsDirectoryExist( output_dir.cstr() ) )
		{
			FileSystem::NewDirectory( output_dir.cstr() );
		}

		if ( clearOutputDir )
		{
			_core->ClearDir( output_dir );
		}

		FOR( i, obj.sounds )
		{
			string	in_fname;
			string	out_fname;

			FileAddressUtils::BuildPath( in_fname, input_dir, obj.sounds[i] );
			FileAddressUtils::BuildPath( out_fname, output_dir, obj.sounds[i], obj.extension );

			CHECK_ERR( _ConvertFont( in_fname, out_fname ) );
		}

		return true;
	}


	// _ConvertFont
	bool SoundConverter::_ConvertFont (uni_c_string inputFile, uni_c_string outputFile)
	{
		// TODO: delete meta info

		RFilePtr	rfile;
		CHECK_ERR( (rfile = File::HddRFile::New( inputFile )).IsNotNull() );

		WFilePtr	wfile;
		CHECK_ERR( (wfile = File::HddWFile::New( outputFile )).IsNotNull() );
		

		SoundHeader	header;

		const uni_c_string	ext = FileAddressUtils::GetExtension( inputFile );

		if ( ext.ICmp( "mp3" ) )	header.fmt = SoundHeader::MP3;	else
		if ( ext.ICmp( "ogg" ) )	header.fmt = SoundHeader::OGG;	else
		if ( ext.ICmp( "wav" ) )	header.fmt = SoundHeader::WAV;	else
									header.fmt = 0;


		RESFILE_WRITE_HEADER( wfile, SoundFileInfo );

		wfile->Write( header );

		static_array< uint8, 2<<12 >	buf;
		isize							size = rfile->RemainingSize();


		while ( size > 0 )
		{
			isize	r = rfile->ReadBuf( buf.ptr(), buf.Size() );

			if ( r > 0 )
			{
				wfile->Write( buf.ptr(), r );
				size -= r;
			}
			else
			{
				RETURN_ERR( "error while convert sound" );
			}
		}

		return true;
	}


}	// Utils
}	// Engine